package com.aitesting.component;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component  //自动加载到spring boot容器
@Aspect //标记为切面类
@Slf4j
public class WebLogAspect {
    /**
     * 定义一个切点，名字叫webLog
     * execution(方法修饰符 返回类型 方法所属的包.类名.方法名称(方法参数)
     */
    @Pointcut("execution(public * com.test.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 目标方法之前会写日志信息
     * @param joinPoint 被切对象
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        //获取当前正在请求的所有属性
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }

        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteAddr();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //获取访问方法的包名和方法名
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        log.info(String.format("用户[%s],在[%s],访问了[%s]", ip, time, target));

    }
}
